package com.uduemc.biso.node.web.api.validator.currentsite.impl;

import java.io.IOException;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.web.api.component.RequestHolder;
import com.uduemc.biso.node.web.api.component.SpringContextUtils;
import com.uduemc.biso.node.web.api.dto.download.DownloadFile;
import com.uduemc.biso.node.web.api.service.RepertoryService;
import com.uduemc.biso.node.web.api.validator.currentsite.CurrentSiteDownloadFileRepertoryId;

public class CurrentSiteDownloadFileRepertoryIdValid
		implements ConstraintValidator<CurrentSiteDownloadFileRepertoryId, DownloadFile> {

	private static final Logger logger = LoggerFactory.getLogger(CurrentSiteDownloadFileRepertoryIdValid.class);

	@Override
	public void initialize(CurrentSiteDownloadFileRepertoryId constraintAnnotation) {

	}

	@Override
	public boolean isValid(DownloadFile value, ConstraintValidatorContext context) {
		long id = value.getId();

		RequestHolder requestHolder = SpringContextUtils.getBean("requestHolder", RequestHolder.class);
		RepertoryService repertoryServiceImpl = SpringContextUtils.getBean("repertoryServiceImpl",
				RepertoryService.class);
		HRepertory hRepertory = null;
		try {
			hRepertory = repertoryServiceImpl.getInfoByid(id);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (hRepertory == null) {
			return false;
		}
		if (hRepertory.getHostId().longValue() != requestHolder.getHost().getId().longValue()) {
			logger.error("CurrentHRepertoryIdValid 验证 " + value + " 不是当前站点（"
					+ requestHolder.getHost().getId().longValue() + "）的资源数据");
			return false;
		}
		return true;
	}

}
